﻿#include "serial.h"
#include "lidar_data.h"
#include <atomic>
#include <thread>
#include <chrono>
#include <mutex>
#include <cmath>
#include <list>
#include <atomic>
#include <vector>
#include <condition_variable>
#include <functional>
#ifndef CAMSENSE_INCLUDE_CAMSENSE_LIDAR_H_
#define CAMSENSE_INCLUDE_CAMSENSE_LIDAR_H_
typedef unsigned char BYTE;

namespace camsense {

class LidarDevice {
 public:
  LidarDevice() = default;
  ~LidarDevice() = default;

  /// \brief 初始化雷达类
  /// \param callback　回调函数
  /// \param port　串口地址
  /// \param baud　波特率
  /// \return　返回值:0，表示成功; 非零表示失败
  int Initialize(std::function<void(const std::vector<RangeData> &)> callback,
                 const std::string &port,
                 unsigned int baud = 230400);
  /// \brief 释放雷达类
  /// \return　返回值:0，表示成功; 非零表示失败
  int Release();
  static int64_t GetTimeStamp();
 private:
  int OpenSerial(const char *port, unsigned int bauds);
  void CloseSerial();
  std::pair<int64_t, RangeDataInfo> ReadDataSerial(unsigned int TimeOut_ms = 50);
  static bool CheckData(const BYTE *buffer, int len);
  static std::vector<RangeData> CorrectRangeData(std::pair<int64_t, RangeDataInfo> &package);
  void LoopReadSerial();
  void LoopSendData();

  static constexpr float center_base_line_ = 11.3;   //非线性补偿时的基准距离
  static constexpr float center_base_line_square_ = center_base_line_ * center_base_line_;   //非线性补偿时的基准距离

  Serial serial_;
  bool is_scanning_{};
  std::thread read_thread_;
  std::thread send_thread_;
  std::mutex mutex_;
  std::condition_variable condition_variable_;
  std::array<std::pair<int64_t, RangeDataInfo>,32> array_ector_;
  uint64_t write_index = 0;
  uint64_t read_index = 0;
  std::function<void(const std::vector<RangeData> &)> data_callback_;
};
}

#endif //CAMSENSE_INCLUDE_CAMSENSE_LIDAR_H_
